<?php
/**
 * Created by PhpStorm.
 * User: wjj
 * Date: 2016/11/1
 */

namespace app\logic;

use app\models\Category;
use yii;

class CategoryLogic
{

    public function getCategorys(){
        return Category::find()->asArray()->all();
    }

    public function getAllCategory($query = [], $page = 1, $limit = 10){
        $category = Category::find()
            ->filterWhere($query)
            ->orderBy('category_sort')
            ->offset(($page - 1) * $limit)->limit($limit);
        $lists = $category->asArray()->all();
        $return = [
            'lists' => $lists,
            'pager' => [
                'total' => $category->count(),
                'page' => $page,
                'limit' => $limit,
                'url' => 'category/index',
                'query' => $query
            ]
        ];
        return $return;
    }

    public function addCategory($params){
        $category = new Category();
        $category->category_name = $params['category_name'];
        $category->category_sort = $params['category_sort'];
        return $category->save();
    }

    public function getById($id)
    {
        return Category::find()->where(['category_id' => $id])->asArray()->one();
    }

    public function editById($id, $params)
    {
        if(!$category = Category::findOne($id)) return false;
        $category->category_name = $params['category_name'];
        $category->category_sort = $params['category_sort'];
        return $category->save();
    }

    public function delete($id)
    {
        $category = Category::findOne($id);
        return $category->delete();
    }
}